<template>
    <main style="position: relative;">
        <mdui-top-app-bar scroll-target=".scroll">
            <mdui-top-app-bar-title>单词表</mdui-top-app-bar-title>
            <div style="flex-grow: 1"></div>
            <div>
                <mdui-button variant="tonal" :class="{ mm_all_btn: true, more_border_all: isManyManage }"
                    @click="chall">反选</mdui-button>
                <mdui-button variant="tonal" :class="{ mm_rem_btn: true, more_rem_btn: isManyManage }"
                    @click="removeAll">删除</mdui-button>
                <mdui-button variant="elevated" @click="isManyManage = !isManyManage"
                    :class="{ mm_btn: true, more_border_btn: isManyManage }">批量管理</mdui-button>

            </div>
            <mdui-button-icon @click="create_sheet">
                <SvgIcon :path="mdiPlus" type="mdi" />
            </mdui-button-icon>
        </mdui-top-app-bar>
        <div class="scroll" @scroll="handleScroll">
            <mdui-card clickable style="width: 100%; height: 124px" v-for="(item, index) in wordSheets" :key="index" @click="start_dictation(item._id,item.name,item.count)"class="word-sheet-card">
                <div :class="{ 'left-btn': true, 'left-btn-hide': isManyManage }">
                    <mdui-checkbox :value="item._id" ref="checkbox_items" @click.stop></mdui-checkbox>
                </div>
                <div :class="{ 'content': true, 'content-is-mm': isManyManage }">
                    
                    <span style="line-height: 50px;padding-left: 10px;font-size: 18px;">{{ item.name }}</span><br>
                    <span style="line-height: 20px;padding-left: 10px;font-size: 13px;">单词总数：{{ item.count
                    }}</span><br>
                    <span style="line-height: 20px;padding-left: 10px;font-size: 13px;">创建时间：{{
                        formatTime(item.created_at) }}</span><br>
                    <span style="line-height: 20px;padding-left: 10px;font-size: 13px;">最后修改时间：{{
                        formatTime(item.edit_at) }}</span>

                </div>
                <div class="right-btn"
                    :style="{ opacity: isManyManage ? '0' : '1', filter: isManyManage ? 'blur(5px)' : 'none' }">
                    <mdui-button-icon @click.stop="router.push({ name: 'edit', params: { id: item._id } })">
                        <SvgIcon :path="mdiPencil" type="mdi" />
                    </mdui-button-icon>
                    <mdui-button-icon @click.stop="remove_sheet(item._id, item.name)">
                        <SvgIcon :path="mdiDelete" type="mdi" />
                    </mdui-button-icon>

                </div>
            </mdui-card>
        </div>
        <mdui-fab style="position: absolute;bottom: 20px;right: 20px;" @click="serachDialog = !serachDialog">
            <SvgIcon :path="mdiMagnify" type="mdi" slot="icon" />
        </mdui-fab>
    </main>

    <mdui-dialog close-on-overlay-click :open="serachDialog">
        <span slot="headline">搜索单词表</span>

        <mdui-text-field label="输入关键词" @input="searchipt = $event.target.value" :value="searchipt"></mdui-text-field>
        <mdui-list>
            <mdui-list-item v-for="item in searchResult" :key="item._id"
                @click="start_dictation(item._id, item.name); serachDialog = false">
                {{ item.name }}

                <span slot="description">
                    单词数量：{{ item.count }} <br>
                    创建时间：{{ formatTime(item.created_at) }} <br>
                    修改时间：{{ formatTime(item.edit_at) }}
                </span>
            </mdui-list-item>
        </mdui-list>

        <mdui-button slot="action" variant="text" @click="serachDialog = false">取消</mdui-button>
        <mdui-button slot="action" variant="tonal" @click="serachDialog = false">确定</mdui-button>

    </mdui-dialog>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import SvgIcon from '@jamescoyle/vue-icon'
import { mdiPlus, mdiDelete, mdiPencil, mdiMagnify } from '@mdi/js'
import { prompt } from "mdui/functions/prompt.js";
import { snackbar } from 'mdui/functions/snackbar.js';
import { confirm } from "mdui/functions/confirm.js";
import { alert } from 'mdui/functions/alert.js';
import router from '@/router';
import { formatTime } from '@/assets/helper';

// 数据存储
const wordSheets = ref([]) // 存储单词表数据
const page = ref(1) // 当前页码
const perPage = ref(10) // 每页数量
const totalPages = ref(1) // 总页数
const loading = ref(false) // 是否正在加载
const isManyManage = ref(false) // 是否批量管理
const checkbox_items = ref(null) // 用于存储复选框引用
const serachDialog = ref(false)
const searchipt = ref('')
const searchResult = ref([])
// 获取数据
async function fetchData() {
    if (loading.value || page.value > totalPages.value) return
    loading.value = true

    try {
        const response = await fetch(`${window.server}/api/get_word_sheets?page=${page.value}&per_page=${perPage.value}`)
        const result = await response.json()

        if (result.message == "获取成功") {
            wordSheets.value = [...wordSheets.value, ...result.data]
            totalPages.value = result.pagination.total_pages
        }
    } catch (error) {
        console.error("获取数据失败:", error)
    }

    loading.value = false
}

// 滚动监听
function handleScroll(event) {
    const container = event.target
    // 判断是否滚动到底部
    if (container.scrollHeight - container.scrollTop <= container.clientHeight + 1) {
        page.value += 1
        fetchData()
    }
}

// 初始化加载第一页数据
onMounted(() => {
    fetchData()
})

watch(searchipt, (newData) => {
    if (newData == "") {
        searchResult.value = []
        return
    }
    fetch(`${window.server}/api/search_word_sheet?query=${searchipt.value}`).then(res => res.json()).then(data => {
        searchResult.value = data.data
    }).catch(err => {
        console.log(err)
        snackbar({
            message: "请求错误，请稍后再试",
        });
    })
})
watch(serachDialog, (newData) => {
    searchipt.value = ""
})

const create_sheet = () => {
    prompt({
        headline: "创建单词表",
        description: "请输入单词表名称",
        confirmText: "创建",
        cancelText: "取消",
        onConfirm: (value) => {
            if (value) {
                fetch(`${window.server}/api/create_word_sheet`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ name: value })
                })
                    .then(response => response.json())
                    .then(result => {
                        if (result.message === "创建成功") {
                            //wordSheets.value.unshift({ name: value });
                            snackbar({
                                message: "创建成功",
                            });


                            // 跳转编辑
                            router.push({
                                name: 'edit',
                                params: { id: result.id }
                            });
                        } else {
                            snackbar({
                                message: "创建失败：" + result.message,
                            });
                        }
                    })
                    .catch(error => {
                        console.error("创建单词表失败:", error);
                        snackbar({
                            message: "创建单词表失败，请稍后再试",
                        });
                    });
            }
        }
    });
}

const remove_sheet = (id, name) => {
    confirm({
        headline: "删除单词表",
        description: "确定要删除单词表" + name + "吗？",
        confirmText: "删除",
        cancelText: "取消",
        onConfirm: () => {
            fetch(`${window.server}/api/delete_word_sheet`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ id: [id] })
            })
                .then(response => response.json())
                .then(result => {
                    if (result.message === "Success") {
                        wordSheets.value = wordSheets.value.filter(sheet => sheet._id !== id);
                        snackbar({
                            message: "删除成功",
                        });
                    } else {
                        snackbar({
                            message: "删除失败：" + result.message,
                        });
                    }
                })
                .catch(error => {
                    console.error("删除单词表失败:", error);
                    snackbar({
                        message: "删除单词表失败，请稍后再试",
                    });
                });
        }

    })
}

const chall = () => {
    if (!checkbox_items.value) {
        snackbar({
            message: "没有可选的单词表",
        });
        isManyManage.value = false; // 取消批量管理状态
        return;
    }
    // 如果没全选则全选，如果已经 全选则取消全选
    for (let i = 0; i < checkbox_items.value.length; i++) {
        checkbox_items.value[i].checked = !checkbox_items.value[i].checked;
    }

}

const removeAll = () => {
    if (!checkbox_items.value) {
        snackbar({
            message: "没有可选的单词表",
        });
        isManyManage.value = false; // 取消批量管理状态
        return;
    }
    const selectedIds = checkbox_items.value.filter(item => item.checked).map(item => item.value);
    if (selectedIds.length === 0) {
        snackbar({
            message: "请至少选择一个单词表",
        });
        isManyManage.value = false; // 取消批量管理状态
        return;
    }

    confirm({
        headline: "删除单词表",
        description: `确定要删除 ${selectedIds.length} 个单词表吗？`,
        confirmText: "删除",
        cancelText: "取消",
        onConfirm: () => {
            fetch(`${window.server}/api/delete_word_sheet`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ id: selectedIds })
            })
                .then(response => response.json())
                .then(result => {
                    if (result.message === "Success") {
                        wordSheets.value = wordSheets.value.filter(sheet => !selectedIds.includes(sheet._id));
                        snackbar({
                            message: "删除成功",
                        });

                    } else {
                        snackbar({
                            message: "删除失败：" + result.message,
                        });
                    }
                    isManyManage.value = false; // 取消批量管理状态
                })
                .catch(error => {
                    console.error("删除单词表失败:", error);
                    snackbar({
                        message: "删除单词表失败，请稍后再试",
                    });
                    isManyManage.value = false;
                });
        }
    })
    isManyManage.value = false; // 取消批量管理状态
}

function start_dictation (id,name,count) {
    if (count == 0) {
        alert({
            headline: "提示",
            description: "这个单词表里空空如也~",
            confirmText: "OK",
        });
    } else {
        confirm({
            headline: "开始默写",
            description: "确定要开始默写单词表 " + name + " 吗？",
            confirmText: "开始",
            cancelText: "取消",
            onConfirm: () => {
                router.push({
                    name: 'dictation',
                    params: { id: id }
            });
        }
    })
    }
}
</script>

<style scoped>
main {
    height: 100%;
    width: 100%;
    position: relative;
}

.scroll {
    height: 100%;
    overflow-y: auto;
    overflow-x: hidden;
    padding-left: 10px;
    padding-right: 10px;
    box-sizing: border-box;
}

.word-sheet-card {
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
    margin-bottom: 10px;
    opacity: 0;
    animation: fadeIn 0.3s ease forwards;



    .right-btn {
        transition: all 0.3s ease;
        width: 60px;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        gap: 10px;
    }

    .left-btn {
        transition: all 0.3s ease;
        width: 60px;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        transform: scale(0);
        transform-origin: left;
        opacity: 0;
        filter: blur(5px);
    }

    .content {
        transition: transform 0.3s ease;
        flex-grow: 1;
        padding: 10px;
        box-sizing: border-box;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        transform: translateX(-60px);
    }
}

@keyframes fadeIn {
    from {
        opacity: 0;
    }

    to {
        opacity: 1;
    }

}

.left-btn-hide {
    transform: scale(1) !important;
    opacity: 1 !important;
    filter: blur(0) !important;
}

.content-is-mm {
    transform: translateX(0) !important;
}

.more_border_btn {
    border-radius: 8px 30px 30px 8px !important;

    transform: translateX(0px) !important;
}

.more_border_all {
    border-radius: 30px 8px 8px 30px !important;

    transform: translateX(-8px) scale(1) !important;
    opacity: 1 !important;
    pointer-events: auto !important;

    filter: blur(0) !important;
}

.more_rem_btn {

    border-radius: 8px 8px 8px 8px !important;
    transform: translateX(-4px) scale(1) !important;
    opacity: 1 !important;
    filter: blur(0) !important;
    pointer-events: auto !important;
}

.mm_rem_btn {
    transition: all 0.3s ease, transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
    transition-delay: 50ms;
    border-radius: 30px 30px 30px 30px;
    transform: translateX(80px);
    z-index: 1;
    opacity: 0.2;
    pointer-events: auto;
    filter: blur(5px);
}

.mm_btn {
    transition: all 0.3s ease;
    border-radius: 30px 30px 30px 30px;

    transform: translateX(0px);
    z-index: 3;
}

.mm_all_btn {
    transition: all 0.3s ease, transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
    transition-delay: 70ms;
    border-radius: 30px 30px 30px 30px;
    opacity: 0;
    pointer-events: none;
    z-index: 2;
    transform: scale(0.8) translateX(160px);
    filter: blur(5px);
}
</style>